<template>
  <mt-popup v-model="visible" position="bottom" style="width:100%;">
    <div class="mint-datetime" ref="compPicker">
      <mt-picker class="mint-datetime-picker"
                 :slots="slots"
                 value-key="name"
                 :visible-item-count="visibleItemCount"
                 @change="onValuesChange"
                 showToolbar>
          <span class="mint-datetime-action mint-datetime-cancel"
                @click="handleClose">{{ cancelText }}</span>
        <span class="mint-datetime-action mint-datetime-confirm"
              @click="fillCompany">{{ confirmText }}</span>
      </mt-picker>
    </div>
  </mt-popup>
</template>

<script>
  import Pinyin from '../../utils/pinyin'
  import {GET_STORES} from '../../assets/js/api'

  export default {
    name: 'CompPicker',
    props: {
      value: {
        type: Boolean,
        default: false
      },
      visibleItemCount: {
        type: Number,
        default: 5
      },
      cancelText: {
        type: String,
        default: '取消'
      },
      confirmText: {
        type: String,
        default: '确定'
      },
    },
    data() {
      return {
        visible: false,
        slots: [{
          flex: 1,
          values: [],
          className: 'slot1',
          textAlign: 'center'
        }],
        company_name: '',
        company_id: ''
      }
    },
    mounted() {
      this.initCompany();
      this.$refs.compPicker.getElementsByClassName('picker-center-highlight')[0]
        .className += ' temp-picker-border'
    },
    methods: {
      initCompany() {
        this.$http.get(GET_STORES).then(json => {
          for (let item of json.data) {
            this.slots[0].values.push({name: item.store_name, id: item.id});
          }
        });
      },
      onValuesChange(picker, val) {
        if (val[0]) {
          this.company_name = val[0].name || null;
          this.company_id = val[0].id || null;
        }
      },
      handleClose() {
        this.$emit('pickerClose', (this.visible = false))
      },
      fillCompany(evt) {
        this.handleClose();
        if (this.company_name) {
          let tempStr = this.company_name.substr(0, 4);
          let pinyin = Pinyin.makePy(tempStr);
          if (pinyin instanceof Array) pinyin = pinyin[0];
          this.$emit('complete', this.company_name, this.company_id, pinyin.toLowerCase());
        }
      }
    },
    watch: {
      value(val) {
        this.visible = val;
      },
      visible(val) {
        this.$emit('input', val);
      }
    }
  }
</script>

<style lang="scss">
  .temp-picker-border {
    @mixin bgColor {
      $bgVar: left, #FAFAFA, #5F5F5F, #FAFAFA;
      background: -moz-linear-gradient($bgVar);
      background: -o-linear-gradient($bgVar);
      background: -webkit-linear-gradient($bgVar);
    }
    &:before, &:after {
      @include bgColor;
    }
  }
</style>
